<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <title>星痕共鸣实时战斗数据</title>
    <style>
        body {
            font-family: "Segoe UI", sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 20px;
            text-align: center;
            transition: background-color 0.3s ease, color 0.3s ease;
        }

        h1 {
            color: #2c3e50;
            margin-bottom: 10px;
            transition: color 0.3s ease;
        }

        h3 {
            color: #e67e22;
            font-weight: normal;
            transition: color 0.3s ease;
        }

        button {
            margin: 20px 0;
            padding: 10px 20px;
            font-size: 16px;
            border-radius: 8px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #45a049;
        }

        a {
            text-decoration: none;
        }

        .card {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
            padding: 20px;
            overflow-x: auto;
            transition: background-color 0.3s ease, color 0.3s ease, box-shadow 0.3s ease;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th {
            background-color: #3498db;
            color: white;
            font-weight: bold;
            transition: background-color 0.3s ease;
        }

        td,
        th {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
            transition: border-color 0.3s ease, background-color 0.3s ease;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
            transition: background-color 0.3s ease;
        }

        .watermark {
            pointer-events: none;
            position: fixed;
            top: -100vh;
            left: -100vw;
            width: 300vw;
            height: 300vh;
            z-index: 9999;
            background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" opacity="0.05"><text x="0" y="20" font-size="20">数据仅供参考</text></svg>');
            display: flex;
            transform: rotate(-30deg);
            user-select: none;
            transition: background-image 0.3s ease;
        }

        .background {
            background-image: url("background.png");
            background-size: cover;
            position: fixed;
            height: 100vh;
            width: 100%;
            left: 0;
            bottom: 0;
            z-index: -1;
            background-repeat: no-repeat;
        }

        /* 夜间模式样式 */
        .dark-mode {
            background-color: #1a1a1a !important;
            color: #e0e0e0 !important;
        }

        .dark-mode h1 {
            color: #4fc3f7 !important;
        }

        .dark-mode h3 {
            color: #ff9800 !important;
        }

        .dark-mode .card {
            background: #2d2d2d !important;
            color: #e0e0e0 !important;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3) !important;
        }

        .dark-mode th {
            background-color: #1976d2 !important;
        }

        .dark-mode tr:nth-child(even) {
            background-color: #383838 !important;
        }

        .dark-mode button {
            background-color: #424242 !important;
            color: #e0e0e0 !important;
        }

        .dark-mode button:hover {
            background-color: #616161 !important;
        }

        .dark-mode td {
            border-color: #555 !important;
        }

        .dark-mode th {
            border-color: #555 !important;
        }

        .dark-mode footer {
            color: #aaa !important;
        }

        .dark-mode footer a {
            color: #4fc3f7 !important;
        }

        .dark-mode .watermark {
            background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100" opacity="0.08"><text x="0" y="20" font-size="20" fill="white">数据仅供参考</text></svg>') !important;
        }

        .dark-mode select {
            background-color: #424242 !important;
            color: #e0e0e0 !important;
            border-color: #666 !important;
        }

        .dark-mode label {
            color: #e0e0e0 !important;
        }

        /* 昵称管理器夜间模式样式 */
        .dark-mode #nicknameModal .content {
            background: #2d2d2d !important;
            color: #e0e0e0 !important;
        }

        .dark-mode #nicknameModal input {
            background-color: #424242 !important;
            color: #e0e0e0 !important;
            border-color: #666 !important;
        }

        .dark-mode #nicknameModal div {
            border-color: #666 !important;
        }

        /* 技能统计弹窗样式 */
        .skill-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 10000;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .skill-content {
            background: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 800px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .skill-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }

        .skill-table th {
            background-color: #e74c3c;
            color: white;
            font-weight: bold;
            padding: 12px;
            text-align: center;
        }

        .skill-table td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: center;
        }

        .skill-table tr:nth-child(even) {
            background-color: #f2f2f2;
        }

        .skill-table tr:hover {
            background-color: #e8f4f8;
        }

        .percentage-bar {
            background-color: #e74c3c;
            height: 20px;
            border-radius: 10px;
            position: relative;
            margin: 5px 0;
        }

        .percentage-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-weight: bold;
            font-size: 12px;
        }

        /* 夜间模式技能统计样式 */
        .dark-mode .skill-content {
            background: #2d2d2d !important;
            color: #e0e0e0 !important;
        }

        .dark-mode .skill-table th {
            background-color: #c0392b !important;
        }

        .dark-mode .skill-table td {
            border-color: #555 !important;
        }

        .dark-mode .skill-table tr:nth-child(even) {
            background-color: #383838 !important;
        }

        .dark-mode .skill-table tr:hover {
            background-color: #34495e !important;
        }
    </style>
</head>

<body>
    <h1>🎯 星痕共鸣实时战斗数据展示 V2.1</h1>
    <h3>⚠ 暂未区分治疗量与伤害量，将合并计算，数据仅供参考</h3>
    <div style="margin: 20px 0;">
        <label for="sortSelect" style="margin-right: 10px; font-weight: bold;">排序方式:</label>
        <select id="sortSelect" onchange="updateSortMode()" style="padding: 8px 12px; font-size: 14px; border-radius: 5px; border: 1px solid #ddd; background-color: white;">
            <option value="uid">按UID排序 (升序)</option>
            <option value="nickname">按昵称排序 (升序)</option>
            <option value="damage">按总伤害排序 (降序)</option>
            <option value="dps">按总DPS排序 (降序)</option>
            <option value="realtimeDpsMax">按最大瞬时DPS排序 (降序)</option>
        </select>
    </div>
    <button onclick="clearData()">✨ 清空统计数据</button>
    <button onclick="showNicknameManager()">👤 管理昵称</button>
    <button onclick="toggleDarkMode()">🌙 夜间模式</button>

    <div class="card">
        <table id="damageTable">
            <thead>
                <tr>
                    <th title="角色唯一标识符">角色 ID</th>
                    <th title="角色昵称">角色 昵称</th>
                    <th title="角色在战斗中造成的总伤害和治疗量">总伤害/治疗</th>
                    <th title="角色在战斗中造成的非幸运的暴击伤害和治疗量">纯暴击</th>
                    <th title="角色在战斗中造成的非暴击的幸运伤害和治疗量">纯幸运</th>
                    <th title="角色在战斗中造成的暴击的幸运伤害和治疗量">暴击幸运</th>
                    <th title="角色在战斗中的暴击触发率">暴击率</th>
                    <th title="角色在战斗中的幸运触发率">幸运率</th>
                    <th title="角色在战斗中的最近一秒造成的伤害和治疗量">瞬时DPS/HPS</th>
                    <th title="角色在战斗中的最大瞬时DPS/HPS">最大瞬时</th>
                    <th title="角色在战斗中的总DPS/HPS（以第一次技能与最后一次技能之间的时间作为有效战斗时间计算）">总DPS/HPS</th>
                    <th title="角色的平均每秒伤害（基于最近10秒数据）">每秒伤害</th>
                    <th title="点击查看技能伤害占比统计">技能统计</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

    <div class="watermark"></div>

    <footer style="margin-top: 40px; font-size: 14px; color: #888;">Copyright © 2025 Made with ❤️ by <a href="https://dml.ink" target="_blank">Dimole</a></footer>

    <script>
        let currentSortMode = 'uid'; // 默认按UID排序
        let lastDataHash = ''; // 用于检测数据是否发生变化

        // 昵称管理函数
        function getNickname(uid) {
            const nicknames = JSON.parse(localStorage.getItem('player_nicknames') || '{}');
            return nicknames[uid] || `玩家_${uid}`;
        }

        async function saveNickname(uid, nickname) {
            // 保存到本地存储
            const nicknames = JSON.parse(localStorage.getItem('player_nicknames') || '{}');
            nicknames[uid] = nickname;
            localStorage.setItem('player_nicknames', JSON.stringify(nicknames));
            
            // 同时保存到服务器
            try {
                const response = await fetch('/api/update-nickname', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        uid: uid,
                        nickname: nickname
                    })
                });
                
                const result = await response.json();
                if (result.code !== 0) {
                    console.warn('服务器保存昵称失败:', result.msg);
                }
            } catch (error) {
                console.warn('服务器保存昵称时出错:', error);
            }
        }

        function getAllNicknames() {
            return JSON.parse(localStorage.getItem('player_nicknames') || '{}');
        }

        async function fetchDataAndUpdateTables() {
            try {
                const res = await fetch('/api/data');
                const data = await res.json();
                
                // 计算数据哈希值，检查是否有变化
                const dataHash = JSON.stringify(data);
                if (dataHash === lastDataHash) {
                    return; // 数据没有变化，不需要更新
                }
                lastDataHash = dataHash;
                
                const damageTable = document.getElementById('damageTable').querySelector('tbody');
                damageTable.innerHTML = '';
                
                // 将数据转换为数组以便排序，并添加昵称
                const userArray = Object.keys(data.user).map(id => ({
                    id: Number(id),
                    nickname: getNickname(id),
                    ...data.user[id]
                }));
                
                // 根据当前排序模式排序
                sortUserArray(userArray);
                
                // 生成表格行
                for (const user of userArray) {
                    const crit_rate = user.total_count.critical / user.total_count.total;
                    const lucky_rate = user.total_count.lucky / user.total_count.total;
                    
                    // 创建表格行元素
                    const row = document.createElement('tr');
                    
                    // 角色ID
                    const idCell = document.createElement('td');
                    idCell.textContent = user.id;
                    row.appendChild(idCell);
                    
                    // 角色昵称（可点击编辑）
                    const nicknameCell = document.createElement('td');
                    const nicknameSpan = document.createElement('span');
                    nicknameSpan.textContent = user.nickname;
                    nicknameSpan.style.cssText = 'cursor: pointer; color: #007bff; text-decoration: underline;';
                    nicknameSpan.title = '点击编辑昵称';
                    nicknameSpan.onclick = () => editNickname(user.id, user.nickname);
                    nicknameCell.appendChild(nicknameSpan);
                    row.appendChild(nicknameCell);
                    

                    
                    // 总伤害/治疗（普通显示，不可点击）
                    const damageCell = document.createElement('td');
                    damageCell.textContent = user.total_damage.total;
                    row.appendChild(damageCell);
                    
                    // 其他数据单元格
                    const cells = [
                        user.total_damage.critical,
                        user.total_damage.lucky,
                        user.total_damage.crit_lucky,
                        (crit_rate * 100).toFixed(2) + '%',
                        (lucky_rate * 100).toFixed(2) + '%',
                        user.realtime_dps,
                        user.realtime_dps_max,
                        user.total_dps.toFixed(2),
                        user.second_damage ? user.second_damage.toFixed(2) : '0.00'
                    ];
                    
                    cells.forEach(cellData => {
                        const cell = document.createElement('td');
                        cell.textContent = cellData;
                        row.appendChild(cell);
                    });
                    
                    // 技能统计按钮（最后一列）
                    const skillStatsCell = document.createElement('td');
                    const skillButton = document.createElement('button');
                    skillButton.textContent = '📊 查看技能';
                    skillButton.style.cssText = 'background-color: #17a2b8; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer; font-size: 12px;';
                    skillButton.title = '点击查看技能伤害占比统计';
                    skillButton.onclick = () => showSkillStats(user.id, user.nickname);
                    skillStatsCell.appendChild(skillButton);
                    row.appendChild(skillStatsCell);
                    
                    damageTable.appendChild(row);
                }
            } catch (err) {
                console.error('获取数据失败：', err);
            }
        }

        function sortUserArray(userArray) {
            switch (currentSortMode) {
                case 'damage':
                    userArray.sort((a, b) => b.total_damage.total - a.total_damage.total);
                    break;
                case 'uid':
                    userArray.sort((a, b) => a.id - b.id);
                    break;
                case 'nickname':
                    userArray.sort((a, b) => a.nickname.localeCompare(b.nickname, 'zh-CN'));
                    break;
                case 'dps':
                    userArray.sort((a, b) => b.total_dps - a.total_dps);
                    break;
                case 'realtimeDpsMax':
                    userArray.sort((a, b) => b.realtime_dps_max - a.realtime_dps_max);
                    break;
                default:
                    userArray.sort((a, b) => a.id - b.id);
                    break;
            }
        }

        function updateSortMode() {
            const select = document.getElementById('sortSelect');
            currentSortMode = select.value;
            localStorage.setItem('sortMode', currentSortMode);
            fetchDataAndUpdateTables();
        }

        async function clearData() {
            const res = await fetch('/api/clear');
            const data = await res.json();
            fetchDataAndUpdateTables();
        }

        function toggleDarkMode() {
            const body = document.body;
            const isDarkMode = body.classList.contains('dark-mode');
            const button = event.target;
            
            if (isDarkMode) {
                body.classList.remove('dark-mode');
                button.textContent = '🌙 夜间模式';
                localStorage.setItem('darkMode', 'false');
            } else {
                body.classList.add('dark-mode');
                button.textContent = '☀️ 日间模式';
                localStorage.setItem('darkMode', 'true');
            }
        }

        // 页面加载时检查本地存储的主题偏好和排序偏好
        function initTheme() {
            const isDarkMode = localStorage.getItem('darkMode') === 'true';
            const body = document.body;
            const button = document.querySelector('button[onclick="toggleDarkMode()"]');
            
            if (isDarkMode) {
                body.classList.add('dark-mode');
                button.textContent = '☀️ 日间模式';
            }
        }

        function initSortMode() {
            const savedSortMode = localStorage.getItem('sortMode');
            if (savedSortMode) {
                currentSortMode = savedSortMode;
                document.getElementById('sortSelect').value = savedSortMode;
            }
        }

        // 编辑昵称功能
        function editNickname(uid, currentNickname) {
            console.log('编辑昵称被调用:', uid, currentNickname);
            const newNickname = prompt('请输入新的昵称:', currentNickname);
            if (newNickname && newNickname.trim() !== '' && newNickname !== currentNickname) {
                saveNickname(uid, newNickname.trim());
                console.log('昵称设置成功');
                fetchDataAndUpdateTables(); // 刷新表格
            }
        }

        // 显示昵称管理器
        function showNicknameManager() {
            // 获取当前所有玩家数据
            fetch('/api/data')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        const users = data.user;
                        let managerHtml = '<div style="max-height: 400px; overflow-y: auto;">';
                        managerHtml += '<h4>🎯 昵称管理器</h4>';
                        managerHtml += '<p>点击下方输入框可以编辑昵称，昵称保存在浏览器本地存储中</p>';
                        
                        for (const uid in users) {
                            const nickname = getNickname(uid);
                            managerHtml += `
                                <div style="margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                                    <label style="display: block; margin-bottom: 5px;">
                                        <strong>UID: ${uid}</strong> (当前昵称: ${nickname})
                                    </label>
                                    <input type="text" id="nickname_${uid}" value="${nickname}" 
                                           style="width: 100%; padding: 5px; border: 1px solid #ccc; border-radius: 3px;"
                                           placeholder="请输入昵称...">
                                </div>
                            `;
                        }
                        
                        managerHtml += '</div>';
                        managerHtml += '<div style="margin-top: 15px; text-align: center;">';
                        managerHtml += '<button onclick="saveAllNicknames()" style="margin-right: 10px; background-color: #28a745;">💾 保存所有昵称</button>';
                        managerHtml += '<button onclick="clearAllNicknames()" style="margin-right: 10px; background-color: #dc3545; color: white;">🗑️ 清空所有昵称</button>';
                        managerHtml += '<button onclick="closeNicknameManager()">❌ 关闭</button>';
                        managerHtml += '</div>';
                        
                        // 创建弹窗
                        const modal = document.createElement('div');
                        modal.id = 'nicknameModal';
                        modal.style.cssText = `
                            position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
                            background-color: rgba(0,0,0,0.5); z-index: 10000; 
                            display: flex; justify-content: center; align-items: center;
                        `;
                        
                        const content = document.createElement('div');
                        content.className = 'content';
                        content.style.cssText = `
                            background: white; padding: 20px; border-radius: 10px; 
                            max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto;
                            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                        `;
                        content.innerHTML = managerHtml;
                        
                        modal.appendChild(content);
                        document.body.appendChild(modal);
                    }
                })
                .catch(error => {
                    console.error('获取玩家数据失败:', error);
                    alert('获取玩家数据失败，请稍后再试');
                });
        }

        // 保存所有昵称
        async function saveAllNicknames() {
            const modal = document.getElementById('nicknameModal');
            const inputs = modal.querySelectorAll('input[id^="nickname_"]');
            let successCount = 0;
            
            for (const input of inputs) {
                const uid = input.id.replace('nickname_', '');
                const nickname = input.value.trim();
                
                if (nickname) {
                    await saveNickname(uid, nickname);
                    successCount++;
                    console.log(`设置UID ${uid} 的昵称: ${nickname}`);
                }
            }
            
            alert(`昵称保存完成！成功保存: ${successCount} 个昵称`);
            closeNicknameManager();
            fetchDataAndUpdateTables(); // 刷新表格
        }

        // 清空所有昵称
        function clearAllNicknames() {
            if (confirm('确定要清空所有昵称设置吗？此操作无法撤销！')) {
                localStorage.removeItem('player_nicknames');
                alert('所有昵称已清空！');
                closeNicknameManager();
                fetchDataAndUpdateTables(); // 刷新表格
            }
        }

        // 关闭昵称管理器
        function closeNicknameManager() {
            const modal = document.getElementById('nicknameModal');
            if (modal) {
                document.body.removeChild(modal);
            }
        }

        // 显示技能统计弹窗
        async function showSkillStats(uid, nickname) {
            console.log('显示技能统计被调用:', uid, nickname);
            try {
                const response = await fetch(`/api/skill-stats/${uid}`);
                const data = await response.json();
                
                if (data.code !== 0) {
                    alert('获取技能统计数据失败：' + data.msg);
                    return;
                }
                
                const skills = data.data;
                if (skills.length === 0) {
                    alert('该玩家暂无技能统计数据');
                    return;
                }
                
                let modalHtml = `
                    <div class="skill-content">
                        <h3>🎯 ${nickname} (UID: ${uid}) 技能伤害占比统计</h3>
                        <p>点击技能名称可以编辑技能名称（保存在浏览器本地存储中）</p>
                        <table class="skill-table">
                            <thead>
                                <tr>
                                    <th>技能ID</th>
                                    <th>技能名称</th>
                                    <th>总伤害</th>
                                    <th>使用次数</th>
                                    <th>伤害占比</th>
                                    <th>占比图表</th>
                                </tr>
                            </thead>
                            <tbody>
                `;
                
                // 获取所有技能名称
                const skillNamesResponse = await fetch('/api/skill-names');
                const skillNamesResult = await skillNamesResponse.json();
                const skillNames = skillNamesResult.code === 0 ? skillNamesResult.data : {};
                
                for (const skill of skills) {
                    const customSkillName = skillNames[skill.skill_id] || skill.skill_name;
                    const percentageBar = `<div class="percentage-bar" style="width: ${skill.percentage}%;"><div class="percentage-text">${skill.percentage}%</div></div>`;
                    
                    modalHtml += `
                        <tr>
                            <td>${skill.skill_id}</td>
                            <td><span class="skill-name-edit" data-uid="${uid}" data-skill-id="${skill.skill_id}" data-skill-name="${customSkillName.replace(/"/g, '&quot;')}" style="cursor: pointer; color: #007bff; text-decoration: underline;" title="点击编辑技能名称">${customSkillName}</span></td>
                            <td>${skill.total_damage.toLocaleString()}</td>
                            <td>${skill.count}</td>
                            <td>${skill.percentage}%</td>
                            <td style="width: 200px;">${percentageBar}</td>
                        </tr>
                    `;
                }
                
                modalHtml += `
                            </tbody>
                        </table>
                        <div style="margin-top: 15px; text-align: center;">
                            <button onclick="closeSkillStats()" style="background-color: #6c757d; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">关闭</button>
                        </div>
                    </div>
                `;
                
                // 创建弹窗
                const modal = document.createElement('div');
                modal.id = 'skillModal';
                modal.className = 'skill-modal';
                modal.innerHTML = modalHtml;
                
                document.body.appendChild(modal);
                
                // 添加技能名称编辑的事件委托
                modal.addEventListener('click', function(e) {
                    if (e.target.classList.contains('skill-name-edit')) {
                        const uid = e.target.getAttribute('data-uid');
                        const skillId = e.target.getAttribute('data-skill-id');
                        const skillName = e.target.getAttribute('data-skill-name');
                        editSkillName(uid, skillId, skillName);
                    }
                });
                
            } catch (error) {
                console.error('获取技能统计数据失败：', error);
                alert('获取技能统计数据失败，请稍后再试');
            }
        }

        // 编辑技能名称
        function editSkillName(uid, skillId, currentName) {
            const newName = prompt('请输入新的技能名称:', currentName);
            if (newName && newName.trim() !== '' && newName !== currentName) {
                saveSkillName(uid, skillId, newName.trim());
                console.log('技能名称设置成功');
            }
        }

        // 保存技能名称到服务器
        async function saveSkillName(uid, skillId, skillName) {
            try {
                const response = await fetch('/api/update-skill-name', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        skillId: skillId,
                        skillName: skillName
                    })
                });
                
                const result = await response.json();
                if (result.code === 0) {
                    console.log('技能名称已保存到服务器配置文件');
                    // 重新显示技能统计弹窗以更新显示
                    const modal = document.getElementById('skillModal');
                    if (modal) {
                        document.body.removeChild(modal);
                    }
                    // 获取昵称并重新显示
                    const nickname = getNickname(uid);
                    showSkillStats(uid, nickname);
                } else {
                    console.error('保存技能名称失败:', result.msg);
                    alert('保存技能名称失败: ' + result.msg);
                }
            } catch (error) {
                console.error('保存技能名称时出错:', error);
                alert('保存技能名称时出错，请稍后再试');
            }
        }

        // 获取技能名称（从服务器获取）
        async function getSkillName(skillId, defaultName) {
            try {
                const response = await fetch('/api/skill-names');
                const result = await response.json();
                if (result.code === 0) {
                    return result.data[skillId] || defaultName;
                }
            } catch (error) {
                console.error('获取技能名称失败:', error);
            }
            return defaultName;
        }

        // 关闭技能统计弹窗
        function closeSkillStats() {
            const modal = document.getElementById('skillModal');
            if (modal) {
                document.body.removeChild(modal);
            }
        }

        setInterval(fetchDataAndUpdateTables, 2000); // 改为2秒更新一次
        fetchDataAndUpdateTables();
        initTheme();
        initSortMode();
        
        // 添加全局点击事件监听，作为备用机制
        document.addEventListener('click', function(e) {
            // 检查是否是昵称编辑点击
            if (e.target.style.color === 'rgb(0, 123, 255)' && e.target.style.textDecoration === 'underline' && e.target.title === '点击编辑昵称') {
                const uid = e.target.closest('tr').cells[0].textContent;
                const nickname = e.target.textContent;
                editNickname(uid, nickname);
            }
            
            // 检查是否是技能统计点击
            if (e.target.style.color === 'rgb(231, 76, 60)' && e.target.style.textDecoration === 'underline' && e.target.title === '点击查看技能伤害占比') {
                const uid = e.target.closest('tr').cells[0].textContent;
                const nickname = e.target.closest('tr').cells[1].textContent;
                showSkillStats(uid, nickname);
            }
        });
    </script>
</body>

</html>